require('dotenv').config();
const jwt = require('jsonwebtoken');
const fs = require('fs');
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
mongoose.set('strictQuery', true);
const userRoutes = require('./routes/userRoutes');
const app = express();

// 跨域中间件
app.use(cors({
 origin: process.env.CLIENT_ORIGIN || 'http://localhost:5173',
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true
}));

app.use(express.json());

const PORT = process.env.PORT || 5000;
app.use('/api/users', userRoutes);

// 连接数据库
mongoose.connect(process.env.MONGODB_URI)
  .then(() => {
    console.log('MongoDB连接成功');

    // 数据库连接成功后挂载路由
    app.use('/api/users', userRoutes);

    // 启动服务器
    app.listen(PORT, () => {
      console.log(`Server started on port ${PORT}`);
    });
  })
  .catch(err => console.error('数据库连接失败:', err));

// 路由
app.get('/', (req, res) => {
  res.send('API Running!');
});



